package com.huahua.api.repository;

import com.huahua.api.entity.pojo.CloudPrintDevice;
import org.springframework.data.r2dbc.repository.Query;
import org.springframework.data.repository.reactive.ReactiveCrudRepository;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;

/**
 * @author Huahua-Ai
 * @date 2025-07-24 17:48:00
 * @description 云打印设备Repository
 */
@Repository
public interface CloudPrintDeviceRepository extends ReactiveCrudRepository<CloudPrintDevice, Long> {

    /**
     * 根据设备ID查找设备
     */
    Mono<CloudPrintDevice> findByDeviceId(String deviceId);

    /**
     * 查找所有在线设备
     */
    Flux<CloudPrintDevice> findByStatusAndIsActive(String status, Boolean isActive);

    /**
     * 根据设备ID更新心跳时间和状态
     */
    @Query("UPDATE cloud_print_device SET last_heartbeat = :heartbeat, status = :status WHERE device_id = :deviceId")
    Mono<Integer> updateHeartbeat(String deviceId, LocalDateTime heartbeat, String status);

    /**
     * 根据设备ID更新状态
     */
    @Query("UPDATE cloud_print_device SET status = :status WHERE device_id = :deviceId")
    Mono<Integer> updateStatus(String deviceId, String status);

    /**
     * 查找指定时间之前的设备（用于检测离线）
     */
    Flux<CloudPrintDevice> findByStatusAndLastHeartbeatBefore(String status, LocalDateTime time);

    /**
     * 检查设备是否存在
     */
    Mono<Boolean> existsByDeviceId(String deviceId);
}
